<template>
  <div class="evaluation-dashboard">
    <el-card class="dashboard-header">
      <div class="header-content">
        <div class="title-section">
          <h1 class="page-title">评价分析仪表板</h1>
          <p class="page-subtitle">智能分析乘客评价，提供改进建议</p>
        </div>
        <div class="action-section">
          <el-button @click="goHome" type="info" icon="House">
            返回主页
          </el-button>
          <el-button type="primary" @click="refreshData" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
          <el-button @click="refreshCharts" type="success">
            刷新图表
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-grid">
      <el-card class="stat-card" v-for="stat in stats" :key="stat.title">
        <div class="stat-content">
          <div class="stat-icon" :style="{ backgroundColor: stat.color }">
            <el-icon><component :is="stat.icon" /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value">{{ stat.value }}</div>
            <div class="stat-title">{{ stat.title }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>评价分布</span>
                <el-select v-model="selectedDriver" placeholder="选择司机" clearable @change="loadChartData">
                  <el-option
                    v-for="driver in driverList"
                    :key="driver.value"
                    :label="driver.label"
                    :value="driver.value"
                  />
                </el-select>
              </div>
            </template>
            <div class="chart-container">
              <div ref="ratingChartRef" class="chart"></div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>改进建议统计</span>
              </div>
            </template>
            <div class="chart-container">
              <div ref="suggestionChartRef" class="chart"></div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 最近分析记录 -->
    <el-card class="recent-analysis">
      <template #header>
        <div class="card-header">
          <span>最近分析记录</span>
          <el-button type="primary" @click="viewAllAnalysis">查看全部</el-button>
        </div>
      </template>
      <el-table :data="recentAnalysis" style="width: 100%" v-loading="tableLoading">
        <el-table-column label="订单号" width="120">
          <template #default="scope">
            {{ getOrderNumber(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column label="司机ID" width="100">
          <template #default="scope">
            {{ getDriverId(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column label="评分" width="100">
          <template #default="scope">
            <div class="rating-display">
              <el-rate v-model="scope.row.order_rating.rating" disabled show-score />
              <span class="rating-text">({{ scope.row.order_rating.rating }})</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="乘客评价" width="200">
          <template #default="scope">
            <el-tooltip 
              :content="getCommentContent(scope.row)" 
              placement="top" 
              :show-after="500"
            >
              <span class="comment-text">
                {{ getCommentContent(scope.row) }}
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="分析结果">
          <template #default="scope">
            {{ getAnalysisResult(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column label="分析时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.analysis_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewAnalysisDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 培训建议 -->
    <el-card class="training-recommendations">
      <template #header>
        <div class="card-header">
          <span>培训建议（显示每个司机的所有培训类型）</span>
          <el-button type="primary" @click="loadTrainingRecommendations" :loading="trainingLoading">
            刷新培训建议
          </el-button>
        </div>
      </template>
      <el-table :data="trainingRecommendations" style="width: 100%" v-loading="trainingLoading">
        <el-table-column label="司机ID" width="100">
          <template #default="scope">
            <el-tag type="info">{{ getDriverInfo(scope.row.driver_id) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="培训类型" width="200">
          <template #default="scope">
            <div class="training-types">
              <el-tag 
                v-for="type in scope.row.recommendation_types" 
                :key="type"
                :type="getTrainingTypeColor(type)"
                style="margin-right: 5px; margin-bottom: 5px;"
              >
                {{ type }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="培训内容" show-overflow-tooltip>
          <template #default="scope">
            <el-tooltip 
              :content="getTrainingContentPreview(scope.row.latest_recommendation.recommendation_content)" 
              placement="top" 
              :show-after="500"
            >
              <span class="training-content">
                {{ getTrainingContentPreview(scope.row.latest_recommendation.recommendation_content) }}
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="优先级" width="120">
          <template #default="scope">
            <div class="priority-summary">
              <el-tag 
                v-for="(count, priority) in scope.row.priority_summary" 
                :key="priority"
                :type="getPriorityColor(parseInt(priority))"
                size="small"
                style="margin-right: 3px;"
              >
                {{ getPriorityText(parseInt(priority)) }}:{{ count }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="120">
          <template #default="scope">
            <div class="status-summary">
              <el-tag 
                v-for="(count, status) in scope.row.status_summary" 
                :key="status"
                :type="getStatusColor(parseInt(status))"
                size="small"
                style="margin-right: 3px;"
              >
                {{ getStatusText(parseInt(status)) }}:{{ count }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="总数" width="80">
          <template #default="scope">
            <el-tag type="info">{{ scope.row.total_count }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            {{ formatTime(scope.row.latest_recommendation.created_time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewDriverTrainingDetail(scope.row)">
              查看详情
            </el-button>
            <el-button 
              v-if="hasUnpushedRecommendations(scope.row)" 
              type="success" 
              size="small" 
              @click="pushAllDriverRecommendations(scope.row)"
            >
              推送全部
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 快速分析 -->
    <el-card class="quick-analysis">
      <template #header>
        <span>快速分析</span>
      </template>
      <el-form :model="quickAnalysisForm" label-width="100px">
        <el-form-item label="选择评价">
          <el-select 
            v-model="quickAnalysisForm.orderRatingId" 
            placeholder="请选择要分析的评价"
            style="width: 100%"
            @change="onRatingSelect"
          >
            <el-option
              v-for="rating in availableRatings"
              :key="rating.id"
              :label="`评价ID: ${rating.id} - 订单: ${rating.order_id} - 评分: ${rating.rating}星`"
              :value="rating.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="quickAnalyze" :loading="quickAnalyzeLoading">
            开始分析
          </el-button>
          <el-button @click="loadAvailableRatings" :loading="loading">
            刷新评价列表
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Refresh, House } from '@element-plus/icons-vue'
import { evaluationAPI } from '@/api/evaluation'
import * as echarts from 'echarts'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const tableLoading = ref(false)
const quickAnalyzeLoading = ref(false)
const trainingLoading = ref(false)
const selectedDriver = ref(null)
const driverList = ref([])
const recentAnalysis = ref([])
const availableRatings = ref([])
const trainingRecommendations = ref([])
const quickAnalysisForm = ref({
  orderRatingId: ''
})

// 图表容器ref
const ratingChartRef = ref(null)
const suggestionChartRef = ref(null)

// 统计卡片数据
const stats = ref([
  { title: '总评价数', value: 0, icon: 'ChatDotRound', color: '#409EFF' },
  { title: '已分析', value: 0, icon: 'Check', color: '#67C23A' },
  { title: '改进建议', value: 0, icon: 'Lightbulb', color: '#E6A23C' },
  { title: '培训建议', value: 0, icon: 'Reading', color: '#F56C6C' }
])

// 图表实例
let ratingChart = null
let suggestionChart = null

// 初始化页面
onMounted(async () => {
  await loadDriverList()
  await loadDashboardData()
  await loadRecentAnalysis()
  await loadAvailableRatings()
  await loadTrainingRecommendations()
  await nextTick()
  initCharts()
})

// 加载司机列表
async function loadDriverList() {
  try {
    const response = await evaluationAPI.getEvaluationAnalysisList({
      page: 1,
      page_size: 1000
    })
    
    if (response.data && response.data.data) {
      const driverIds = new Set()
      response.data.data.forEach(analysis => {
        if (analysis.order_rating && analysis.order_rating.driver_id) {
          driverIds.add(analysis.order_rating.driver_id)
        }
      })
      
      driverList.value = Array.from(driverIds).map(id => ({
        value: id,
        label: `司机 ${id}`
      }))
      
      console.log('加载的司机列表:', driverList.value)
      
      // 如果没有司机数据，添加一个默认选项
      if (driverList.value.length === 0) {
        console.log('没有找到司机数据，添加默认选项')
        driverList.value = [
          { value: 81, label: '司机 81' }
        ]
      }
    }
  } catch (error) {
    console.error('加载司机列表失败:', error)
    ElMessage.error('加载司机列表失败')
  }
}

// 加载仪表板数据
async function loadDashboardData() {
  loading.value = true
  try {
    const response = await evaluationAPI.getEvaluationDashboard(selectedDriver.value)
    if (response.data) {
      const data = response.data
      stats.value[0].value = data.total_ratings || 0
      stats.value[1].value = data.analyzed_ratings || 0
      stats.value[2].value = data.improvement_suggestions || 0
      stats.value[3].value = data.training_recommendations || 0
    }
  } catch (error) {
    console.error('加载仪表板数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 加载最近分析记录
async function loadRecentAnalysis() {
  tableLoading.value = true
  try {
    const response = await evaluationAPI.getEvaluationAnalysisList({
      page: 1,
      page_size: 10
    })
    console.log('分析记录API响应:', response)
    if (response.data) {
      recentAnalysis.value = response.data.data || []
      console.log('设置分析记录数据:', recentAnalysis.value)
      
      // 打印每个分析记录的详细信息
      recentAnalysis.value.forEach((analysis, index) => {
        console.log(`分析记录 ${index + 1} 详细信息:`, {
          id: analysis.id,
          order_rating: analysis.order_rating,
          sentiment_label: analysis.sentiment_label,
          key_phrases: analysis.key_phrases,
          improvement_areas: analysis.improvement_areas,
          analysis_time: analysis.analysis_time
        })
      })
      
      // 数据加载完成后更新图表
      setTimeout(() => {
        updateRatingChart()
        updateSuggestionChart()
      }, 200)
    }
  } catch (error) {
    console.error('加载分析记录失败:', error)
    ElMessage.error('加载分析记录失败')
  } finally {
    tableLoading.value = false
  }
}

// 初始化图表
function initCharts() {
  // 延迟初始化图表，确保DOM已经渲染
  setTimeout(() => {
    console.log('开始初始化图表')
    updateRatingChart()
    updateSuggestionChart()
  }, 500)
}

// 更新评价分布图表
function updateRatingChart() {
  console.log('开始更新评价分布图表')
  
  // 使用ref访问图表容器
  const ratingChartDom = ratingChartRef.value
  console.log('图表容器:', ratingChartDom)
  
  if (ratingChartDom) {
    console.log('图表容器尺寸:', ratingChartDom.offsetWidth, 'x', ratingChartDom.offsetHeight)
    
    if (!ratingChart) {
      ratingChart = echarts.init(ratingChartDom)
      console.log('初始化评价分布图表')
    }
    
    let filteredData = recentAnalysis.value
    console.log('原始数据:', filteredData)
    console.log('选择的司机:', selectedDriver.value)
    
    // 如果没有选择司机，则不显示数据
    if (!selectedDriver.value) {
      console.log('未选择司机，显示空图表')
      filteredData = []
    } else {
      // 只显示当前选择司机的数据
      filteredData = recentAnalysis.value.filter(analysis => 
        analysis.order_rating && analysis.order_rating.driver_id == selectedDriver.value
      )
      console.log(`司机 ${selectedDriver.value} 的评价数据:`, filteredData)
    }
    
    const ratingStats = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 }
    filteredData.forEach(analysis => {
      const rating = analysis.order_rating && analysis.order_rating.rating
      if (rating && rating >= 1 && rating <= 5) {
        ratingStats[rating]++
      }
    })
    
    console.log(`司机 ${selectedDriver.value} 的评分统计:`, ratingStats)
    
    const chartData = [
      { value: ratingStats[5], name: '5星' },
      { value: ratingStats[4], name: '4星' },
      { value: ratingStats[3], name: '3星' },
      { value: ratingStats[2], name: '2星' },
      { value: ratingStats[1], name: '1星' }
    ].filter(item => item.value > 0)
    
    console.log('图表数据:', chartData)
    
    // 如果没有选择司机，显示空状态
    let finalChartData
    if (!selectedDriver.value) {
      finalChartData = []
    } else {
      // 使用真实数据
      finalChartData = chartData
    }
    
    console.log('最终图表数据:', finalChartData)
    
    const ratingOption = {
      title: {
        text: selectedDriver.value ? `司机 ${selectedDriver.value} 评价分布` : '请选择司机查看评价分布',
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        show: selectedDriver.value && finalChartData.length > 0
      },
      series: [
        {
          name: '评价分布',
          type: 'pie',
          radius: '50%',
          data: selectedDriver.value && finalChartData.length > 0 ? finalChartData : [],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }
    
    try {
      ratingChart.setOption(ratingOption, true) // 添加true参数强制更新
      console.log('评价分布图表更新成功')
    } catch (error) {
      console.error('评价分布图表更新失败:', error)
    }
  } else {
    console.error('未找到评价分布图表容器')
  }
}

// 更新改进建议统计图表
function updateSuggestionChart() {
  console.log('开始更新改进建议统计图表')
  
  // 使用ref访问图表容器
  const suggestionChartDom = suggestionChartRef.value
  console.log('改进建议图表容器:', suggestionChartDom)
  
  if (suggestionChartDom) {
    console.log('改进建议图表容器尺寸:', suggestionChartDom.offsetWidth, 'x', suggestionChartDom.offsetHeight)
    
    if (!suggestionChart) {
      suggestionChart = echarts.init(suggestionChartDom)
      console.log('初始化改进建议统计图表')
    }
    
    // 从分析数据中统计改进建议类型
    const suggestionStats = {
      '服务态度': 0,
      '驾驶技术': 0,
      '车辆状况': 0,
      '沟通能力': 0,
      '时间观念': 0
    }
    
    let chartData, categories
    
    // 如果没有选择司机，则不显示数据
    if (!selectedDriver.value) {
      console.log('未选择司机，改进建议图表显示为空')
      chartData = [0, 0, 0, 0, 0]
      categories = ['服务态度', '驾驶技术', '车辆状况', '沟通能力', '时间观念']
    } else {
      // 只统计当前选择司机的改进建议数据
      const driverAnalysis = recentAnalysis.value.filter(analysis => 
        analysis.order_rating && analysis.order_rating.driver_id == selectedDriver.value
      )
      
      console.log(`司机 ${selectedDriver.value} 的分析记录:`, driverAnalysis)
      
      // 重新统计当前司机的改进建议
      const driverSuggestionStats = {
        '服务态度': 0,
        '驾驶技术': 0,
        '车辆状况': 0,
        '沟通能力': 0,
        '时间观念': 0
      }
      
      // 统计分析记录中的改进建议
      driverAnalysis.forEach((analysis, index) => {
        console.log(`司机 ${selectedDriver.value} 的分析记录 ${index + 1}:`, analysis)
        if (analysis.improvement_areas && Array.isArray(analysis.improvement_areas)) {
          console.log(`司机 ${selectedDriver.value} 记录 ${index + 1} 的改进领域:`, analysis.improvement_areas)
          analysis.improvement_areas.forEach(area => {
            if (area.area && driverSuggestionStats.hasOwnProperty(area.area)) {
              driverSuggestionStats[area.area]++
            }
          })
        }
      })
      
      // 统计培训建议中的改进建议
      const driverTrainingRecommendations = trainingRecommendations.value.filter(rec => 
        rec.driver_id == selectedDriver.value
      )
      
      console.log(`司机 ${selectedDriver.value} 的培训建议:`, driverTrainingRecommendations)
      
      driverTrainingRecommendations.forEach((rec, index) => {
        console.log(`司机 ${selectedDriver.value} 培训建议 ${index + 1}:`, rec)
        if (rec.training_type && driverSuggestionStats.hasOwnProperty(rec.training_type)) {
          driverSuggestionStats[rec.training_type]++
        }
      })
      
      console.log(`司机 ${selectedDriver.value} 的改进建议统计:`, driverSuggestionStats)
      
      chartData = Object.values(driverSuggestionStats)
      categories = Object.keys(driverSuggestionStats)
      
      // 如果没有数据，添加一些测试数据
      if (chartData.every(val => val === 0)) {
        console.log('没有找到数据，添加测试数据')
        chartData = [2, 1, 3, 0, 1]
      }
    }
    
    const suggestionOption = {
      title: {
        text: selectedDriver.value ? `司机 ${selectedDriver.value} 改进建议统计` : '请选择司机查看改进建议统计',
        left: 'center'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: categories
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '建议数量',
          type: 'bar',
          data: chartData,
          itemStyle: {
            color: '#409EFF'
          }
        }
      ]
    }
    
    console.log('改进建议统计图表配置:', suggestionOption)
    console.log('图表数据:', chartData)
    console.log('图表类别:', categories)
    
    try {
      suggestionChart.setOption(suggestionOption, true) // 添加true参数强制更新
      console.log('改进建议统计图表更新成功')
    } catch (error) {
      console.error('改进建议统计图表更新失败:', error)
    }
  } else {
    console.error('未找到改进建议统计图表容器')
  }
}

// 刷新数据
async function refreshData() {
  console.log('开始刷新数据')
  await loadDriverList()
  await loadDashboardData()
  await loadRecentAnalysis()
  ElMessage.success('数据已刷新')
}

// 刷新图表
function refreshCharts() {
  console.log('手动刷新图表')
  ratingChart = null
  suggestionChart = null
  setTimeout(() => {
    updateRatingChart()
    updateSuggestionChart()
  }, 100)
  ElMessage.success('图表已刷新')
}



// 加载图表数据
async function loadChartData() {
  console.log('司机选择变化，重新加载图表数据')
  // 重置图表实例，确保重新初始化
  ratingChart = null
  suggestionChart = null
  setTimeout(() => {
    updateRatingChart()
    updateSuggestionChart()
  }, 100)
}

// 查看分析详情
function viewAnalysisDetail(analysis) {
  console.log('查看分析详情，数据:', analysis)
  if (!analysis || !analysis.id) {
    ElMessage.error('无效的分析记录')
    return
  }
  
  try {
    console.log('导航到:', `/evaluation/detail/${analysis.id}`)
    router.push(`/evaluation/detail/${analysis.id}`)
  } catch (error) {
    console.error('路由导航失败:', error)
    ElMessage.error('页面跳转失败')
  }
}

// 查看全部分析
function viewAllAnalysis() {
  router.push('/evaluation/list')
}

// 返回主页
function goHome() {
  router.push('/')
}

// 加载可用评价
async function loadAvailableRatings() {
  try {
    const response = await evaluationAPI.getEvaluationDashboard(selectedDriver.value, { show_available: true })
    if (response.data && response.data.data) {
      availableRatings.value = response.data.data
    }
  } catch (error) {
    console.error('加载可用评价失败:', error)
    ElMessage.error('加载评价列表失败')
  }
}

// 选择评价
function onRatingSelect(ratingId) {
  console.log('选择的评价ID:', ratingId)
}

// 快速分析
async function quickAnalyze() {
  if (!quickAnalysisForm.value.orderRatingId) {
    ElMessage.warning('请选择要分析的评价')
    return
  }

  quickAnalyzeLoading.value = true
  try {
    const response = await evaluationAPI.analyzeEvaluation(quickAnalysisForm.value.orderRatingId)
    if (response.data && response.data.success) {
      ElMessage.success('分析完成')
      quickAnalysisForm.value.orderRatingId = ''
      await refreshData()
    } else {
      ElMessage.error(response.data?.error || '分析失败')
    }
  } catch (error) {
    console.error('快速分析失败:', error)
    ElMessage.error('分析失败')
  } finally {
    quickAnalyzeLoading.value = false
  }
}

// 加载培训建议
async function loadTrainingRecommendations() {
  trainingLoading.value = true
  try {
    const response = await evaluationAPI.getTrainingRecommendations(selectedDriver.value)
    if (response.data && response.data.data) {
      // 按司机ID分组，显示每个司机的所有培训类型
      const groupedRecommendations = {}
      response.data.data.forEach(recommendation => {
        const driverId = recommendation.driver_id
        if (!groupedRecommendations[driverId]) {
          groupedRecommendations[driverId] = []
        }
        groupedRecommendations[driverId].push(recommendation)
      })
      
      // 为每个司机创建汇总记录
      const summaryRecommendations = []
      Object.entries(groupedRecommendations).forEach(([driverId, recommendations]) => {
        // 按创建时间排序
        recommendations.sort((a, b) => new Date(b.created_time) - new Date(a.created_time))
        
        // 创建汇总记录
        const summaryRecord = {
          driver_id: parseInt(driverId),
          recommendation_types: recommendations.map(r => r.recommendation_type),
          all_recommendations: recommendations,
          latest_recommendation: recommendations[0], // 最新的培训建议
          total_count: recommendations.length,
          status_summary: getStatusSummary(recommendations),
          priority_summary: getPrioritySummary(recommendations)
        }
        summaryRecommendations.push(summaryRecord)
      })
      
      // 按司机ID排序
      trainingRecommendations.value = summaryRecommendations.sort((a, b) => a.driver_id - b.driver_id)
      
      console.log('按司机分组的培训建议:', trainingRecommendations.value)
    }
  } catch (error) {
    console.error('加载培训建议失败:', error)
    ElMessage.error('加载培训建议失败')
  } finally {
    trainingLoading.value = false
  }
}

// 推送培训建议
async function pushTrainingRecommendation(id) {
  try {
    const response = await evaluationAPI.pushTrainingRecommendation(id)
    if (response.data && response.data.message) {
      ElMessage.success('培训建议推送成功')
      // 重新加载培训建议，确保分组逻辑正确
      await loadTrainingRecommendations()
    } else {
      ElMessage.error(response.data?.error || '推送失败')
    }
  } catch (error) {
    console.error('推送培训建议失败:', error)
    ElMessage.error('推送失败')
  }
}

// 查看培训建议详情
function viewTrainingDetail(id) {
  if (!id) {
    ElMessage.error('无效的培训建议ID')
    return
  }
  router.push(`/training/detail/${id}`)
}

// 格式化日期
function formatDate(dateString) {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 格式化时间
function formatTime(dateString) {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleTimeString('zh-CN', { hour: 'numeric', minute: 'numeric' })
}

// 获取订单号
function getOrderNumber(row) {
  return row.order_rating && row.order_rating.order && row.order_rating.order.order_number 
    ? row.order_rating.order.order_number 
    : 'N/A'
}

// 获取司机ID
function getDriverId(row) {
  return row.order_rating && row.order_rating.driver_id 
    ? row.order_rating.driver_id 
    : 'N/A'
}

// 获取评价内容
function getCommentContent(row) {
  return row.order_rating && row.order_rating.comment 
    ? row.order_rating.comment 
    : '暂无评价内容'
}

// 获取分析结果
function getAnalysisResult(row) {
  return row.analysis_result || '暂无分析结果'
}

// 获取司机信息
function getDriverInfo(driverId) {
  const driver = driverList.value.find(d => d.value == driverId)
  return driver ? driver.label : `司机 ${driverId}`
}

// 获取培训类型颜色
function getTrainingTypeColor(type) {
  switch (type) {
    case '服务态度':
      return 'success'
    case '驾驶技术':
      return 'info'
    case '车辆状况':
      return 'warning'
    case '沟通能力':
      return 'primary'
    case '时间观念':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取优先级颜色
function getPriorityColor(priority) {
  switch (priority) {
    case 1:
      return 'info'
    case 2:
      return 'warning'
    case 3:
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态颜色
function getStatusColor(status) {
  switch (status) {
    case 0:
      return 'info'
    case 1:
      return 'success'
    case 2:
      return 'warning'
    default:
      return 'info'
  }
}

// 获取优先级文本
function getPriorityText(priority) {
  switch (priority) {
    case 1:
      return '低'
    case 2:
      return '中'
    case 3:
      return '高'
    default:
      return '未知'
  }
}

// 获取状态文本
function getStatusText(status) {
  switch (status) {
    case 0:
      return '未推送'
    case 1:
      return '已推送'
    case 2:
      return '已查看'
    case 3:
      return '已完成'
    default:
      return '未知'
  }
}

// 获取培训内容预览
function getTrainingContentPreview(content) {
  if (!content) return '暂无内容'
  
  // 如果是字符串，去掉Markdown符号后截取
  if (typeof content === 'string') {
    const cleanContent = content
      .replace(/^#{1,6}\s*/gm, '') // 去掉标题的#号
      .replace(/\*\*(.*?)\*\*/g, '$1') // 去掉粗体的**号
      .replace(/\*(.*?)\*/g, '$1') // 去掉斜体的*号
      .replace(/^###\s*/gm, '') // 去掉三级标题
      .replace(/^####\s*/gm, '') // 去掉四级标题
      .replace(/^-\s*/gm, '• ') // 将-替换为• 
      .trim()
    
    if (cleanContent.length > 50) {
      return cleanContent.substring(0, 50) + '...'
    }
    return cleanContent
  }
  
  // 如果是对象，转换为字符串
  try {
    const contentStr = JSON.stringify(content)
    if (contentStr.length > 50) {
      return contentStr.substring(0, 50) + '...'
    }
    return contentStr
  } catch (e) {
    return '内容格式错误'
  }
}

// 获取状态汇总
function getStatusSummary(recommendations) {
  const statusCounts = {}
  recommendations.forEach(rec => {
    const status = rec.status
    statusCounts[status] = (statusCounts[status] || 0) + 1
  })
  return statusCounts
}

// 获取优先级汇总
function getPrioritySummary(recommendations) {
  const priorityCounts = {}
  recommendations.forEach(rec => {
    const priority = rec.priority
    priorityCounts[priority] = (priorityCounts[priority] || 0) + 1
  })
  return priorityCounts
}

// 查看司机所有培训建议详情
function viewDriverTrainingDetail(driverGroup) {
  console.log('点击查看司机详情:', driverGroup)
  console.log('司机ID:', driverGroup.driver_id)
  console.log('培训建议数量:', driverGroup.all_recommendations?.length)
  
  // 验证数据完整性
  if (driverGroup.all_recommendations) {
    driverGroup.all_recommendations.forEach((rec, index) => {
      console.log(`培训建议 ${index + 1}:`, {
        id: rec.id,
        type: rec.recommendation_type,
        status: rec.status,
        priority: rec.priority
      })
    })
  }
  
  // 将司机组数据存储到sessionStorage，供详情页面使用
  sessionStorage.setItem('driverTrainingData', JSON.stringify(driverGroup))
  router.push(`/training/driver/${driverGroup.driver_id}`)
}

// 推送司机所有未推送的培训建议
async function pushAllDriverRecommendations(driverGroup) {
  const unpushedRecommendations = driverGroup.all_recommendations.filter(rec => rec.status === 0)
  if (unpushedRecommendations.length === 0) {
    ElMessage.warning('该司机没有未推送的培训建议')
    return
  }

  try {
    // 逐个推送未推送的培训建议
    for (const recommendation of unpushedRecommendations) {
      const response = await evaluationAPI.pushTrainingRecommendation(recommendation.id)
      if (!response.data || !response.data.message) {
        throw new Error(`推送培训建议 ${recommendation.id} 失败`)
      }
    }
    
    ElMessage.success(`成功推送司机 ${getDriverInfo(driverGroup.driver_id)} 的 ${unpushedRecommendations.length} 条培训建议`)
    // 重新加载培训建议，确保分组逻辑正确
    await loadTrainingRecommendations()
  } catch (error) {
    console.error('推送培训建议失败:', error)
    ElMessage.error('推送失败')
  }
}

// 检查是否有未推送的培训建议
function hasUnpushedRecommendations(driverGroup) {
  return driverGroup.all_recommendations.some(rec => rec.status === 0)
}
</script>

<style scoped>
.evaluation-dashboard {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.comment-text {
  display: inline-block;
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
}

.comment-text:hover {
  color: #409EFF;
  cursor: pointer;
}

.dashboard-header {
  margin-bottom: 20px;
  border-radius: 12px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-section {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.action-section {
  display: flex;
  gap: 12px;
  align-items: center;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 12px;
  transition: transform 0.2s;
}

.stat-card:hover {
  transform: translateY(-2px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.stat-title {
  font-size: 14px;
  color: #909399;
}

.charts-section {
  margin-bottom: 20px;
}

.chart-card {
  border-radius: 12px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
  padding: 20px;
}

.chart {
  width: 100%;
  height: 100%;
}

.recent-analysis {
  margin-bottom: 20px;
  border-radius: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.training-recommendations {
  margin-bottom: 20px;
  border-radius: 12px;
}

.training-content {
  display: inline-block;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
}

.training-content:hover {
  color: #409EFF;
  cursor: pointer;
}

.training-types {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.priority-summary,
.status-summary {
  display: flex;
  flex-wrap: wrap;
  gap: 3px;
}

.quick-analysis {
  border-radius: 12px;
}

.rating-display {
  display: flex;
  align-items: center;
  gap: 4px;
}

.rating-text {
  font-size: 14px;
  color: #909399;
}
</style> 